package com.activities;

import java.util.Calendar;

import com.data.DataManager;
import com.main.R;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AutoCompleteTextView.Validator;

public class Log extends Activity{
	
	private DataManager dbManager;
	
	private TextView mDateDisplay;

    // date and time
    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;
    static final int SUBMIT_ID = 2;
	
	private EditText boxWeight;
	private String value;
	private Long _id;
	private String date;
	private String time;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log_edit);
		// bind view components with the existent in the XML design.
		dbManager = new DataManager(this);
		mDateDisplay = (TextView) findViewById(R.id.dateDisplay);		// text field used to show the current date & time.
		Button pickDate = (Button) findViewById(R.id.pickDate); 		// used to access to the date editor.
		pickDate.setOnClickListener(new LogButtonsOnClickListener(DATE_DIALOG_ID));
        Button pickTime = (Button) findViewById(R.id.pickTime);			// used to access to the time editor.
        pickTime.setOnClickListener(new LogButtonsOnClickListener(TIME_DIALOG_ID));
		boxWeight = (EditText) findViewById(R.id.boxWeight);			// used to insert the weight value.
		Button submit = (Button) this.findViewById(R.id.butSubmit);		// used to submit the data.
		submit.setOnClickListener(new LogButtonsOnClickListener(SUBMIT_ID));
		Bundle extras = getIntent().getExtras();		// gets the data from the intent that belongs to the calling activity.
		if (extras!=null) { 							// data found (editing existing entry).
			bringDataFromExtra(extras);
		} else {
			bringDataFromCalendar();
		}
        updateDisplay();	// updates the display that shows date & time.
	}
	
	private void bringDataFromCalendar() {
		final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
	}
	
	private void bringDataFromExtra(Bundle extras) {
		value = extras.getString(DataManager.KEY_VALUE);
		date = extras.getString(DataManager.KEY_DATE);
		time = extras.getString(DataManager.KEY_TIME);
		_id = extras.getLong(DataManager.KEY_ROWID);
		String[] auxDate = date.split("-");
		String[] auxTime = time.split(":");
		mYear = Integer.parseInt(auxDate[2]);
		mMonth = Integer.parseInt(auxDate[1]);
		mDay = Integer.parseInt(auxDate[0]);
		mMinute = Integer.parseInt(auxTime[1]);
		mHour = Integer.parseInt(auxTime[0]);
	}
	
	private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" ")
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }

    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinute = minute;
                    updateDisplay();
                }
            };

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case TIME_DIALOG_ID:
                ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
            break;
            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
            break;
        }
    }
    
    // Inner class used to handle all buttons clicks.
    
	private class LogButtonsOnClickListener implements OnClickListener {		
		private int id;
		public LogButtonsOnClickListener (int id) { this.id = id; }
		public void onClick(View v) {
			switch (this.id){
				case DATE_DIALOG_ID:
					showDialog(DATE_DIALOG_ID);
				break;
				case TIME_DIALOG_ID:
                	showDialog(TIME_DIALOG_ID);
                break;
				case SUBMIT_ID:
					if (validWeight(boxWeight.getText().toString())) 
						submitLog();
					else 
						popMessage(R.string.invalidData);
				break;
			} 
		}
	}
	
	private boolean validWeight (String weight) {
		try {
			Double.parseDouble(weight);
			return true;
		} catch (IllegalArgumentException ilegal) {
			return false;
		}
	}
	
	private void popMessage(int mes) {
		Toast.makeText(this, mes, Toast.LENGTH_LONG).show();	
	}
	
	private void submitLog() {
		value = boxWeight.getText().toString();
		date = Integer.toString(mDay)
				.concat("-").concat(Integer.toString(mMonth+1))
				.concat("-").concat(Integer.toString(mYear)); 
		time = Integer.toString(mHour)
				.concat(":").concat(Integer.toString(mMinute));
		// fill bundle with the data submitted by the user.
		Bundle bundle = new Bundle();
		bundle.putString(DataManager.KEY_VALUE, value);
		bundle.putString(DataManager.KEY_DATE, date);
		bundle.putString(DataManager.KEY_TIME, time);
		bundle.putString(DataManager.KEY_VALUE, value);
		// set id (just in case that this activity has been called from a ListActivity)
		if (_id != null) {
    	    bundle.putLong(DataManager.KEY_ROWID, _id);
    	}
		dbManager.open();
		dbManager.createNewEntry(value, date, time);
		dbManager.close();
		// TODO: mandar un aviso a la actividad principal para que avise al history q actualice la tabla.
		popMessage(R.string.logSubmitted);
		boxWeight.setText("");
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_options_menu, menu);
        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case R.id.settings:
        	MyActivity.onCreateNewActivity(this, MyActivity.SETTINGS);
            return true;
        case R.id.close:
        	MyActivity.onCreateNewActivity(this, MyActivity.CLOSE_APP);
            return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }
}
